#include "MouseManager.hpp"
#include <GL/glut.h>

MouseManager*  MouseManager::m_instance   = 0;

MouseManager* MouseManager::GetInstance()
{
	if( !m_instance )
	{
		m_instance = new MouseManager;
	}

	return m_instance;
}

MouseManager::MouseManager()
{
	m_clickCounter = 0;
}

void MouseManager::ProcessMouseMotion( int mouse_x, int mouse_y )
{
	// NEEDS TO BE REFACTORED - JUST LIKE THIS WHOLE CLASS.
	// TODO: Proper implementation of mouse processing methods, decreasing variables count - move
	//       camera parameters to new Camera Class.

	//if( moveCam )
	//{
	//	static float xoffset = 0, yoffset = 0, zoffset = 0;
	//	static int lastX = 0, lastY = 0;
	//	float up = 1.0f;
	//	float radius = sqrt( pow(0.0f - x, 2) + pow(0.0f - y, 2) + pow(0.0f - z, 2) );
	//	static float alfa = 0.0f, beta = asinf(m_y/radius);
	//	float deg2rad = PI/180.0f;
	//	float rad2deg = 180.0f/PI;
	//	float alfaOffset, betaOffset;

	//	alfaOffset = (m_x - lastClickX)/1.0 * deg2rad;
	//	betaOffset = (m_y - lastClickY)/1.0 * deg2rad;

	//	alfa += alfaOffset;
	//	beta += betaOffset;

	//	if(alfa*rad2deg >= 360.0f)
	//		alfa = 0.0f;
	//	else if(beta*rad2deg >= 360.0f)
	//		beta = 0.0f;
	//	else if(alfa*rad2deg <= -360.0f)
	//		alfa = 0.0f;
	//	else if(beta*rad2deg <= -360.0f)
	//		beta = 0.0f;

	//	x = sin( alfa ) * radius * cos(  beta  );
	//	y = sin( beta ) * radius;
	//	z = cos( alfa )* radius *cos(  beta );

	//	if( (beta*rad2deg >= 90.0f && beta*rad2deg <= 270.0f ) ||
	//		(beta*rad2deg <= -90.0f && beta*rad2deg >= -270.0f) )
	//		up = -1.0f;
	//	else
	//		up = 1.0f;

	//	glMatrixMode(GL_MODELVIEW);
	//	glLoadIdentity();
	//	gluLookAt(x, y, z, 
	//			  0.0f,0.0f,0.0f,
	//			  0.0f,up,0.0f);

	//	lastClickX = x; lastClickY = y;
	//}
}

void MouseManager::ProcessMouseClicks( int button, int state, int mouse_x, int mouse_y )
{
	if( state == GLUT_DOWN )
		GetInstance()->AddClick();

	if( button == GLUT_LEFT_BUTTON && state == GLUT_DOWN )
	{
		GetInstance()->m_moveCamera = true;
		GetInstance()->m_lastClickX = mouse_x; 
		GetInstance()->m_lastClickY = mouse_y;
	}
	else if( button == GLUT_LEFT_BUTTON && state == GLUT_UP )
	{
		GetInstance()->m_moveCamera = false;
	}
}

const int& MouseManager::GetClickCounter() const
{
	return m_clickCounter;
}

void MouseManager::AddClick()
{
	++m_clickCounter;
}